<?php
class Common
{
    /**
     * @author liqiming
     * @date   2018-12-26
     * @param  string     $path 目录地址
     * @return array
     */
    public static function getDirContent($path)
    {
        if (!is_dir($path)) {
            return false;
        }
        $path = rtrim($path, '/');
        $dir  = opendir($path);
        $arr  = array();
        while ($content = readdir($dir)) {
            if ($content != '.' && $content != '..') {
                $arr[] = [
                    'name'         => $content,
                    'type'         => is_dir($path . '/' . $content) ? 'FOLDER' : 'FILE',
                    'filemtime'    => filemtime($path . '/' . $content),
                    'friendlytime' => self::contextualTime(filemtime($path . '/' . $content)),
                    'size'         => self::calc(filesize($path . '/' . $content)),
                ];
            }
        }
        closedir($dir);
        !empty($arr) && $arr = array_reverse($arr);
        return $arr;
    }

    /**
     * 一个简单的加密和解密的方法
     *
     * @author liqiming
     * @date   2018-03-21
     * @param  string     $string 被加密的字符串
     * @param  string     $action encrypt:加密；decrypt:解密
     *
     * @return string
     */
    public static function endecrypt($string, $action = 'encrypt')
    {
        $output         = false;
        $encrypt_method = "AES-256-CBC";
        $secret_key     = 'TRrVVdEeEM1QWg3WGpyU1';
        $secret_iv      = 'HJUS1o4OVhxWVV6UUxuW';
        // hash
        $key = hash('sha256', $secret_key);

        // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
        $iv = substr(hash('sha256', $secret_iv), 0, 16);
        if ($action == 'encrypt') {
            $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
            $output = base64_encode($output);
        } else if ($action == 'decrypt') {
            $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
        }
        return $output;
    }

    /**
     * 获取微秒
     *
     * @author liqiming
     * @date   2018-12-29
     * @return [type]     [description]
     */
    public static function getMicroTime()
    {
        list($usec, $sec) = explode(" ", microtime());
        return ((float) $usec + (float) $sec);
    }

    //替换资源
    public static function replaceAsset($content, $pre)
    {
        $preg = [
            'css' => '/<link.*?href="(.*?)".*?>/si',
            'js'  => '/<script.*?src="(.*?)".*?>.*?<\/script>/si',
            'img' => '/<img.*?src="(.*?)".*?\/>/si',
        ];
        foreach ($preg as $key => $value) {
            preg_match_all($value, $content, $matches);
            if ($matches[1]) {
                $output = self::replaceAssetArr($matches[1], $pre);
                if ($output['a']) {
                    $content = str_replace($output['a'], $output['b'], $content);
                }
            }
        }
        return $content;
    }

    public static function replaceAssetArr($array, $pre)
    {
        $output = ['a' => [], 'b' => []];
        foreach ($array as $key => $value) {
            if (!strstr($value, 'http:') && !strstr($value, 'https:')) {
                $output['a'][] = $value;
                $output['b'][] = $pre . $value;
            }
        }
        return $output;
    }

    /**
     * 格式化字节
     *
     * @param  integer $size   字节
     * @param  integer $digits 单位
     * @return string 返回字符串
     */
    public static function calc($size, $digits = 2)
    {
        $unit = array('', 'K', 'M', 'G', 'T', 'P');
        $base = 1024;
        $i    = floor(log($size, $base));
        $n    = count($unit);
        if ($i >= $n) {
            $i = $n - 1;
        }
        return round($size / pow($base, $i), $digits) . ' ' . $unit[$i] . 'B';
    }

    public static function contextualTime($small_ts, $large_ts = false, $lang = 'zh')
    {
        $config = [
            'zh' => [
                'last_year'  => '去年',
                'last_month' => '上个月',
                'last_week'  => '上周',
                'less_than'  => '小于',
                'yesterday'  => '昨天',
                'about'      => '大约',
                'a_year'     => '一年',
                'years'      => '年',
                'a_month'    => '一月',
                'months'     => '月',
                'a_week'     => '一周',
                'weeks'      => '周',
                'days'       => '天',
                'hour'       => '小时',
                'minutes'    => '分',
                'seconds'    => '秒',
                'ago'        => '前',
            ],
        ];
        if (!$large_ts) {
            $large_ts = time();
        }

        $n = $large_ts - $small_ts;
        if ($n <= 1) {
            return $config[$lang]['less_than'] . ' 1 ' . $config[$lang]['seconds'] . ' ' . $config[$lang]['ago'];
        }

        if ($n < (60)) {
            return $n . ' ' . $config[$lang]['seconds'] . ' ' . $config[$lang]['ago'];
        }

        if ($n < (60 * 60)) {$minutes = round($n / 60);return $config[$lang]['about'] . ' ' . $minutes . ' ' . $config[$lang]['minutes'] . ' ' . $config[$lang]['ago'];}
        if ($n < (60 * 60 * 16)) {$hours = round($n / (60 * 60));return $config[$lang]['about'] . ' ' . $hours . ' ' . $config[$lang]['hour'] . (($hours > 1 and $lang == 'en') ? 's' : '') . ' ' . $config[$lang]['ago'];}
        if ($n < (time() - strtotime('yesterday'))) {
            return $config[$lang]['yesterday'];
        }

        if ($n < (60 * 60 * 24)) {$hours = round($n / (60 * 60));return $config[$lang]['about'] . ' ' . $hours . ' ' . $config[$lang]['hour'] . (($hours > 1 and $lang == 'en') ? 's' : '') . ' ' . $config[$lang]['ago'];}
        if ($n < (60 * 60 * 24 * 6.5)) {
            return $config[$lang]['about'] . ' ' . round($n / (60 * 60 * 24)) . ' ' . $config[$lang]['days'] . ' ' . $config[$lang]['ago'];
        }

        if ($n < (time() - strtotime('last week'))) {
            return $config[$lang]['last_week'];
        }

        if (round($n / (60 * 60 * 24 * 7)) == 1) {
            return $config[$lang]['about'] . ' ' . $config[$lang]['a_week'] . ' ' . $config[$lang]['ago'];
        }

        if ($n < (60 * 60 * 24 * 7 * 3.5)) {
            return $config[$lang]['about'] . ' ' . round($n / (60 * 60 * 24 * 7)) . ' ' . $config[$lang]['weeks'] . ' ' . $config[$lang]['ago'];
        }

        if ($n < (time() - strtotime('last month'))) {
            return $config[$lang]['last_month'];
        }

        if (round($n / (60 * 60 * 24 * 7 * 4)) == 1) {
            return $config[$lang]['about'] . ' ' . $config[$lang]['a_month'] . ' ' . $config[$lang]['ago'];
        }

        if ($n < (60 * 60 * 24 * 7 * 4 * 11.5)) {
            return $config[$lang]['about'] . ' ' . round($n / (60 * 60 * 24 * 7 * 4)) . ' ' . $config[$lang]['months'] . ' ' . $config[$lang]['ago'];
        }

        if ($n < (time() - strtotime('last year'))) {
            return $config[$lang]['last_year'];
        }

        if (round($n / (60 * 60 * 24 * 7 * 52)) == 1) {
            return $config[$lang]['about'] . ' ' . $config[$lang]['a_year'] . ' ' . $config[$lang]['ago'];
        }

        if ($n >= (60 * 60 * 24 * 7 * 4 * 12)) {
            return $config[$lang]['about'] . ' ' . round($n / (60 * 60 * 24 * 7 * 52)) . ' ' . $config[$lang]['years'] . ' ' . $config[$lang]['ago'];
        }

        return false;
    }

    public static function createdirlist($path, $mode)
    {
        if (is_dir($path)) {
            //判断目录存在否，存在不创建
            echo "目录'" . $path . "'已经存在";
            //已经存在则输入路径
        } else {
            //不存在则创建目录
            $re = mkdir($path, $mode, true);
            //第三个参数为true即可以创建多极目录
            if ($re) {
                echo "目录创建成功"; //目录创建成功
            } else {
                echo "目录创建失败";
            }
        }
    }
}
